Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports Csla
Imports Csla.Data
Imports Csla.Validation


<Serializable()> _
Public Class rw_teamRoot
    Inherits Csla.BusinessBase(Of rw_teamRoot)

#Region " Business Properties and Methods "

    ' declare members
    Private _teamId As Integer = 0
    Private _coachId As Integer = 0
    Private _divisionId As Integer = 0
    Private _teamName As String = String.Empty
    Private _teamNumber As Integer = 0
    Private _playerCount As Integer = 0
    Private _createDate As SmartDate = New SmartDate(DateTime.Today)

    Private _myPlayerChildList As rw_playerChildList = rw_playerChildList.NewPlayerChildList

    ''' <summary>
    ''' Get the TeamId of the current object.
    ''' </summary>
    ''' <value>A Integer that represents the TeamId of the current object.</value>
    ''' <returns>Integer representing the return value.</returns>
    ''' <remarks></remarks>
    <System.ComponentModel.DataObjectField(True, False)> _
    Public ReadOnly Property TeamId() As Integer
        Get
            CanReadProperty("TeamId", True)
            Return _teamId
        End Get
    End Property

    ''' <summary>
    ''' Get or Set the CoachId of the current object.
    ''' </summary>
    ''' <value>A Integer that represents the CoachId of the current object.</value>
    ''' <returns>Integer representing the return value.</returns>
    ''' <remarks></remarks>
    Public Property CoachId() As Integer
        Get
            CanReadProperty("CoachId", True)
            Return _coachId
        End Get
        Set(ByVal value As Integer)
            CanWriteProperty("CoachId", True)
            If Not _coachId.Equals(value) Then
                _coachId = value
                PropertyHasChanged("CoachId")
            End If
        End Set
    End Property

    ''' <summary>
    ''' Get or Set the DivisionId of the current object.
    ''' </summary>
    ''' <value>A Integer that represents the DivisionId of the current object.</value>
    ''' <returns>Integer representing the return value.</returns>
    ''' <remarks></remarks>
    Public Property DivisionId() As Integer
        Get
            CanReadProperty("DivisionId", True)
            Return _divisionId
        End Get
        Set(ByVal value As Integer)
            CanWriteProperty("DivisionId", True)
            If Not _divisionId.Equals(value) Then
                _divisionId = value
                PropertyHasChanged("DivisionId")
            End If
        End Set
    End Property

    ''' <summary>
    ''' Get or Set the TeamName of the current object.
    ''' </summary>
    ''' <value>A String that represents the TeamName of the current object.</value>
    ''' <returns>String representing the return value.</returns>
    ''' <remarks></remarks>
    Public Property TeamName() As String
        Get
            CanReadProperty("TeamName", True)
            Return _teamName
        End Get
        Set(ByVal value As String)
            CanWriteProperty("TeamName", True)
            If value Is Nothing Then value = String.Empty
            If Not _teamName.Equals(value) Then
                _teamName = value
                PropertyHasChanged("TeamName")
            End If
        End Set
    End Property

    ''' <summary>
    ''' Get or Set the TeamNumber of the current object.
    ''' </summary>
    ''' <value>A Integer that represents the TeamNumber of the current object.</value>
    ''' <returns>Integer representing the return value.</returns>
    ''' <remarks></remarks>
    Public Property TeamNumber() As Integer
        Get
            CanReadProperty("TeamNumber", True)
            Return _teamNumber
        End Get
        Set(ByVal value As Integer)
            CanWriteProperty("TeamNumber", True)
            If Not _teamNumber.Equals(value) Then
                _teamNumber = value
                PropertyHasChanged("TeamNumber")
            End If
        End Set
    End Property

    ''' <summary>
    ''' Get or Set the PlayerCount of the current object.
    ''' </summary>
    ''' <value>A Integer that represents the PlayerCount of the current object.</value>
    ''' <returns>Integer representing the return value.</returns>
    ''' <remarks></remarks>
    Public Property PlayerCount() As Integer
        Get
            CanReadProperty("PlayerCount", True)
            Return _playerCount
        End Get
        Set(ByVal value As Integer)
            CanWriteProperty("PlayerCount", True)
            If Not _playerCount.Equals(value) Then
                _playerCount = value
                PropertyHasChanged("PlayerCount")
            End If
        End Set
    End Property

    ''' <summary>
    ''' Get or Set the CreateDate of the current object.
    ''' </summary>
    ''' <value>A DateTime that represents the CreateDate of the current object.</value>
    ''' <returns>DateTime representing the return value.</returns>
    ''' <remarks></remarks>
    Public Property CreateDate() As DateTime
        Get
            CanReadProperty("CreateDate", True)
            Return _createDate.Date
        End Get
        Set(ByVal value As DateTime)
            CanWriteProperty("CreateDate", True)
            If Not _createDate.Equals(value) Then
                _createDate.Date = value
                PropertyHasChanged("CreateDate")
            End If
        End Set
    End Property

    ''' <summary>
    ''' Get or Set the CreateDateString of the current object.
    ''' </summary>
    ''' <value>A String that represents the CreateDateString of the current object.</value>
    ''' <returns>String representing the return value.</returns>
    ''' <remarks></remarks>
    Public Property CreateDateString() As String
        Get
            CanReadProperty("CreateDateString", True)
            Return _createDate.Text
        End Get
        Set(ByVal value As String)
            CanWriteProperty("CreateDateString", True)
            If value Is Nothing Then value = String.Empty
            If Not _createDate.Equals(value) Then
                _createDate.Text = value
                PropertyHasChanged("CreateDateString")
            End If
        End Set
    End Property

    Public ReadOnly Property players() As rw_playerChildList
        Get
            Return _myPlayerChildList
        End Get
    End Property
    ''' <summary>
    ''' Get the unique id for the current object.
    ''' </summary>
    ''' <returns>A value that is the unique id of the object.</returns>
    ''' <remarks></remarks>
    Protected Overrides Function GetIdValue() As Object
        Return _teamId
    End Function

#End Region ' Business Properties and Methods

#Region " Validation Rules "

    Public Overrides ReadOnly Property IsValid() As Boolean
        Get
            Return MyBase.IsValid AndAlso _myPlayerChildList.IsValid
        End Get
    End Property
    Public Overrides ReadOnly Property IsDirty() As Boolean
        Get
            Return MyBase.IsDirty OrElse _myPlayerChildList.IsDirty
        End Get
    End Property

    ''' <summary>
    ''' Method that allows the addition of custom business rules.
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub AddCustomRules()
        'todo: add custom/non-generated rules here...
    End Sub

    ''' <summary>
    ''' Method that allows the addition of shared custom business rules.
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub AddSharedCustomRules()
        'todo: add custom/non-generated shared rules here...
    End Sub

    ''' <summary>
    ''' Method used to instigate the addition of all Business rules both Custom and Common.
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overrides Sub AddInstanceBusinessRules()
        AddCustomRules()
        MyBase.AddBusinessRules()
    End Sub

    ''' <summary>
    ''' Method that allows the addition of shared common business rules.
    ''' </summary>
    ''' <remarks>These rules represent the database defaults that can be generated.</remarks>
    Private Sub AddSharedCommonRules()
        ' TeamName rules
        ValidationRules.AddRule(AddressOf Csla.Validation.CommonRules.StringRequired, "TeamName")
        ValidationRules.AddRule(AddressOf Csla.Validation.CommonRules.StringMaxLength, New Csla.Validation.CommonRules.MaxLengthRuleArgs("TeamName", 50))
        ' CreateDate rules
        ValidationRules.AddRule(AddressOf Csla.Validation.CommonRules.StringRequired, "CreateDateString")
    End Sub

    ''' <summary>
    ''' Method used to instigate the addition of all Business rules both Custom and Common.
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overrides Sub AddBusinessRules()
        AddSharedCommonRules()
        AddSharedCustomRules()
        MyBase.AddBusinessRules()
    End Sub

#End Region ' Validation Rules

#Region " Authorization Rules "

    Protected Overrides Sub AddAuthorizationRules()
        'TODO: Define authorization rules in rw_teamRoot
        'AuthorizationRules.AllowRead("TeamId", "rw_teamRootReadGroup")
        'AuthorizationRules.AllowRead("CoachId", "rw_teamRootReadGroup")
        'AuthorizationRules.AllowRead("DivisionId", "rw_teamRootReadGroup")
        'AuthorizationRules.AllowRead("TeamName", "rw_teamRootReadGroup")
        'AuthorizationRules.AllowRead("TeamNumber", "rw_teamRootReadGroup")
        'AuthorizationRules.AllowRead("PlayerCount", "rw_teamRootReadGroup")
        'AuthorizationRules.AllowRead("CreateDate", "rw_teamRootReadGroup")
        'AuthorizationRules.AllowRead("CreateDateString", "rw_teamRootReadGroup")

        'AuthorizationRules.AllowWrite("CoachId", "rw_teamRootWriteGroup")
        'AuthorizationRules.AllowWrite("DivisionId", "rw_teamRootWriteGroup")
        'AuthorizationRules.AllowWrite("TeamName", "rw_teamRootWriteGroup")
        'AuthorizationRules.AllowWrite("TeamNumber", "rw_teamRootWriteGroup")
        'AuthorizationRules.AllowWrite("PlayerCount", "rw_teamRootWriteGroup")
        'AuthorizationRules.AllowWrite("CreateDateString", "rw_teamRootWriteGroup")
    End Sub

    Public Shared Function CanGetObject() As Boolean
        'TODO: Define CanGetObject permission in rw_teamRoot
        Return True
        'If Csla.ApplicationContext.User.IsInRole("rw_teamRootViewGroup") Then
        '	Return True
        'End If
        'Return False
    End Function

    Public Shared Function CanAddObject() As Boolean
        'TODO: Define CanAddObject permission in rw_teamRoot
        Return True
        'If Csla.ApplicationContext.User.IsInRole("rw_teamRootAddGroup") Then
        '	Return True
        'End If
        'Return False
    End Function

    Public Shared Function CanEditObject() As Boolean
        'TODO: Define CanEditObject permission in rw_teamRoot
        Return True
        'If Csla.ApplicationContext.User.IsInRole("rw_teamRootEditGroup") Then
        '	Return True
        'End If
        'Return False
    End Function

    Public Shared Function CanDeleteObject() As Boolean
        'TODO: Define CanDeleteObject permission in rw_teamRoot
        Return True
        'If Csla.ApplicationContext.User.IsInRole("rw_teamRootDeleteGroup") Then
        '	Return True
        'End If
        'Return False
    End Function

#End Region ' Authorization Rules

#Region " Factory Methods "

    Private Sub New()
        ' require use of factory method 
    End Sub

    Public Shared Function NewTeamRoot(ByVal teamId As Integer) As rw_teamRoot
        If Not CanAddObject() Then
            Throw New System.Security.SecurityException("User not authorized to add a rw_teamRoot")
        End If
        Return DataPortal.Create(Of rw_teamRoot)(New Criteria(teamId))
    End Function

    Public Shared Function GetTeamRoot(ByVal teamId As Integer) As rw_teamRoot
        If Not CanGetObject() Then
            Throw New System.Security.SecurityException("User not authorized to view a rw_teamRoot")
        End If
        Return DataPortal.Fetch(Of rw_teamRoot)(New Criteria(teamId))
    End Function

    Public Shared Sub DeleteTeamRoot(ByVal teamId As Integer)
        If Not CanDeleteObject() Then
            Throw New System.Security.SecurityException("User not authorized to remove a rw_teamRoot")
        End If
        DataPortal.Delete(New Criteria(teamId))
    End Sub

    Public Overrides Function Save() As rw_teamRoot
        If IsDeleted AndAlso Not CanDeleteObject() Then
            Throw New System.Security.SecurityException("User not authorized to remove a rw_teamRoot")
        ElseIf IsNew AndAlso Not CanAddObject() Then
            Throw New System.Security.SecurityException("User not authorized to add a rw_teamRoot")
        ElseIf Not CanEditObject() Then
            Throw New System.Security.SecurityException("User not authorized to update a rw_teamRoot")
        End If
        Return MyBase.Save()
    End Function

#End Region ' Factory Methods

#Region " Data Access "

#Region " Criteria "

    <Serializable()> _
    Private Class Criteria

        Public TeamId As Integer

        Public Sub New(ByVal teamId As Integer)
            Me.TeamId = teamId
        End Sub
    End Class

#End Region 'Criteria

#Region " Data Access - Create "

    <RunLocal()> _
    Private Overloads Sub DataPortal_Create(ByVal criteria As Criteria)
        _teamId = criteria.TeamId
        ValidationRules.CheckRules()
    End Sub

#End Region ' Data Access - Create

#Region " Data Access - Fetch "

    Private Overloads Sub DataPortal_Fetch(ByVal criteria As Criteria)
        Dim myConnectionObj As New connection
        Dim myConnection As SqlClient.SqlConnection
        myConnection = myConnectionObj.ReadMySettings()

        Using cn As SqlConnection = New SqlConnection(myConnection.ConnectionString.ToString)
            cn.Open()
            ExecuteFetch(cn, criteria)
        End Using
    End Sub

    Private Sub ExecuteFetch(ByVal cn As SqlConnection, ByVal criteria As Criteria)
        Using cm As SqlCommand = cn.CreateCommand()
            cm.CommandType = CommandType.StoredProcedure
            cm.CommandText = "sp_getTeamInfo"
            cm.Parameters.AddWithValue("@iFilter", 1)
            cm.Parameters.AddWithValue("@teamId", criteria.TeamId)

            Using dr As SafeDataReader = New SafeDataReader(cm.ExecuteReader())
                FetchObject(dr)
                ValidationRules.CheckRules()

                'load child object(s)
                dr.NextResult()
                _myPlayerChildList = rw_playerChildList.GetPlayerChildList(dr)

            End Using
        End Using
    End Sub

    Private Sub FetchObject(ByVal dr As SafeDataReader)
        dr.Read()
        _teamId = dr.GetInt32("teamId")
        _coachId = dr.GetInt32("coachId")
        _divisionId = dr.GetInt32("divisionId")
        _teamName = dr.GetString("teamName")
        _teamNumber = dr.GetInt32("teamNumber")
        _playerCount = dr.GetInt32("playerCount")
        _createDate = dr.GetSmartDate("createDate", _createDate.EmptyIsMin)
    End Sub

    Private Sub FetchChildren(ByVal dr As SafeDataReader)
    End Sub

#End Region ' Data Access - Fetch

#Region " Data Access - Insert "

    Protected Overrides Sub DataPortal_Insert()
        Dim myConnectionObj As New connection
        Dim myConnection As SqlClient.SqlConnection
        myConnection = myConnectionObj.ReadMySettings()

        Using cn As SqlConnection = New SqlConnection(myConnection.ConnectionString.ToString)
            cn.Open()
            ExecuteInsert(cn)

            'update child object(s)
            UpdateChildren(cn)
        End Using
    End Sub

    Private Sub ExecuteInsert(ByVal cn As SqlConnection)
        Using cm As SqlCommand = cn.CreateCommand()
            cm.CommandType = CommandType.StoredProcedure
            cm.CommandText = "sp_insTeamInfo"

            AddInsertParameters(cm)

            cm.ExecuteNonQuery()
            _teamId = CType(cm.Parameters("@new_teamId").Value, Integer)
        End Using
    End Sub

    Private Sub AddInsertParameters(ByVal cm As SqlCommand)
        cm.Parameters.AddWithValue("@coachId", _coachId)
        cm.Parameters.AddWithValue("@divisionId", _divisionId)
        cm.Parameters.AddWithValue("@teamName", _teamName)
        cm.Parameters.AddWithValue("@teamNumber", _teamNumber)
        cm.Parameters.AddWithValue("@playerCount", _playerCount)
        cm.Parameters.AddWithValue("@new_teamId", _teamId)
        cm.Parameters("@new_teamId").Direction = ParameterDirection.Output

    End Sub

#End Region 'Data Access - Insert

#Region " Data Access - Update "

    Protected Overrides Sub DataPortal_Update()
        Dim myConnectionObj As New connection
        Dim myConnection As SqlClient.SqlConnection
        myConnection = myConnectionObj.ReadMySettings()

        Using cn As SqlConnection = New SqlConnection(myConnection.ConnectionString.ToString)
            cn.Open()
            If MyBase.IsDirty Then
                ExecuteUpdate(cn)
            End If

            ' update child object(s)
            UpdateChildren(cn)
        End Using

    End Sub

    Private Sub ExecuteUpdate(ByVal cn As SqlConnection)
        Using cm As SqlCommand = cn.CreateCommand()
            cm.CommandType = CommandType.StoredProcedure
            cm.CommandText = "sp_updTeamInfo"

            AddUpdateParameters(cm)

            cm.ExecuteNonQuery()

        End Using
    End Sub

    Private Sub AddUpdateParameters(ByVal cm As SqlCommand)
        cm.Parameters.AddWithValue("@teamId", _teamId)
        cm.Parameters.AddWithValue("@coachId", _coachId)
        cm.Parameters.AddWithValue("@divisionId", _divisionId)
        cm.Parameters.AddWithValue("@teamName", _teamName)
        cm.Parameters.AddWithValue("@teamNumber", _teamNumber)
        cm.Parameters.AddWithValue("@playerCount", _playerCount)
    End Sub

    Private Sub UpdateChildren(ByVal cn As SqlConnection)
        _myPlayerChildList.Update(cn, Me)
    End Sub

#End Region 'Data Access - Update

#Region " Data Access - Delete "

    Protected Overrides Sub DataPortal_DeleteSelf()
        DataPortal_Delete(New Criteria(_teamId))
    End Sub

    Private Overloads Sub DataPortal_Delete(ByVal criteria As Criteria)
        Dim myConnectionObj As New connection
        Dim myConnection As SqlClient.SqlConnection
        myConnection = myConnectionObj.ReadMySettings()

        Using cn As SqlConnection = New SqlConnection(myConnection.ConnectionString.ToString)
            cn.Open()
            ExecuteDelete(cn, criteria)
        End Using
    End Sub

    Private Sub ExecuteDelete(ByVal cn As SqlConnection, ByVal criteria As Criteria)
        Using cm As SqlCommand = cn.CreateCommand()
            cm.CommandType = CommandType.StoredProcedure
            cm.CommandText = "sp_delTeamInfo"

            cm.Parameters.AddWithValue("@teamId", criteria.TeamId)

            cm.ExecuteNonQuery()
        End Using
    End Sub

#End Region ' Data Access - Delete

#End Region 'Data Access


End Class

